package com.ikun.aimian.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.ikun.aimian.common.BaseResponse;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.common.ResultUtils;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.manager.AiManager;
import com.ikun.aimian.mapper.QuestionMapper;
import com.ikun.aimian.model.entity.App;
import com.ikun.aimian.model.enums.AppTypeEnum;
import com.ikun.aimian.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * AI生成图片接口
 *
 */
@RestController
@RequestMapping("/image")
@Slf4j
public class ImageController {

    @Autowired
    private AppService appService;

    @Autowired
    private AiManager aiManager;

    @Autowired
    QuestionMapper  questionMapper;


    /**
     * 应用的题目的信息
     *
     * @param app
     * @param questionContent
     * @return
     */
    private String getGenerateQuestionMessage(App app, String questionContent) {
        StringBuilder userMessage = new StringBuilder();
        userMessage.append(app.getAppDesc()).append("\n");
        userMessage.append(questionContent);
        return userMessage.toString();
    }

    // AI 生成知识点与难度分布可视化提示词
    private static final String GENERATE_KNOWLEDGE_DIFFICULTY_VISUALIZATION_SYSTEM_MESSAGE =
            "你是一位专业的数据可视化专家，我会给你如下信息：\n" +
                    "```\n" +
                    "【【【应用描述】】】，\n" +
                    "应用题目信息（JSON 数组,每个 option 中的 key为选项，value 为选项对应的答案）\n" +
                    "```\n" +
                    "\n" +
                    "请根据上述信息，严格按照以下步骤来生成用于图像：\n" +
                    "要求：\n" +
                    "   - 【图片里的全部使用英文】；\n" +
                    "   - 【不需要标题】；\n" +
                    "   - 【要清晰可见，越简洁越好，不要其他多余的字】；\n" +
                    "   - 先统计每个知识点下的题目总数，并区分简单与难题数量；\n" +
                    "   - 生成的图片为饼图，难题与简单题分别用不同颜色展示；\n" +
                    "   - 风格简洁、信息突出，易于一目了然地看出各知识点难易题分布；\n" +
                    "```\n";



    @PostMapping("/create")
    public BaseResponse<List<String>> baiLianGenerateQuestion(@RequestParam Long appId) {
        ThrowUtils.throwIf(appId == null, ErrorCode.PARAMS_ERROR);
        // 获取参数
        String questionContent = questionMapper.selectQuestionContentByAppId(appId);
        // 获取应用信息
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
        // 封装 Prompt
        String userMessage = getGenerateQuestionMessage(app, questionContent);
        // AI 生成图片
        ImageSynthesisResult result = aiManager.doBaiLianImageSyncRequest(
                GENERATE_KNOWLEDGE_DIFFICULTY_VISUALIZATION_SYSTEM_MESSAGE,
                userMessage
        );

        // 从结果中提取 URL 列表
        List<Map<String, String>> raws = result.getOutput().getResults();
        List<String> urls = raws.stream()
                .map(m -> m.get("url"))
                .collect(Collectors.toList());
        app.setQuestionIcon(urls.get(0));
        appService.updateById(app);

        return ResultUtils.success(urls);

    }
}
